<template>
  <div class="gl_contentBox gl_heightFull">
    <!-- 筛选项 -->
    <el-row :gutter="20" class="gl_searchBox" style="margin: 0;">
      <el-col :span="6" :lg="4">
        <p>姓名/证件号码</p>
        <el-input v-model="registerQO.Filter" placeholder="请输入姓名/证件号码" size="mini" clearable @change="getPageList()" />
      </el-col>
      <el-col :span="6" :lg="4" class="search_btn">
        <!-- 查询按钮 -->
        <el-button type="primary" size="mini" @click="getMemberList()">{{ $t('button.query') }}</el-button>
        <!-- 重置按钮 -->
        <el-button type="warning" size="mini" @click="initForm()">{{ $t('button.Reset') }}</el-button>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-row :gutter="20" class="gl_my_15">
      <el-col :span="24">
        <el-button type="primary" size="mini" @click="handleOpenEditMemberInfo('add')">新增人员</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="tableLoading" class="gl_mb_15" :data="tableData" stripe size="mini" style="width: 100%">
      <el-table-column label="头像" align="center" :width="95">
        <template slot-scope="{ row }">
          <show-avatar
            :src="getStaticAvatarUrl(row.imagePath)"
            width="74px"
            height="105px"
            style="background-size: 100% 100%;"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" :width="150" />
      <el-table-column label="性别" align="center" :width="70">
        <template slot-scope="{ row }">
          {{ row.gender && row.gender.name }}
        </template>
      </el-table-column>
      <el-table-column prop="nationalityName" label="国籍" align="center" :width="100" />
      <el-table-column label="证件类型" align="center" :width="110">
        <template slot-scope="{ row }">
          {{ row.idCardType && row.idCardType.name }}
        </template>
      </el-table-column>
      <el-table-column prop="idCardNumber" label="证件号" align="center" :width="150" />
      <el-table-column label="所属区域" align="center" :min-width="180">
        <template slot-scope="{ row }">
          {{ addressDataForCheck(row) }}
        </template>
      </el-table-column>
      <el-table-column prop="phoneNumber" label="联系方式" :width="100" />
      <el-table-column label="身份标签" :width="220">
        <template slot-scope="{ row }">
          <el-tag v-for="(item, index) in row.registerTags" :key="index" size="mini" class="gl_mr_5">
            {{ item.registerTagType && item.registerTagType.name || item.registerTagTypeCode }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('table.actions')" align="left" :width="180">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" @click="handleOpenEditMemberInfo('check', row)">
            <span class="gl_color_primary">查看详情</span>
          </el-button>
          <el-button size="mini" type="text" @click="handleOpenEditMemberInfo('edit', row)">
            <span class="gl_color_primary">编辑</span>
          </el-button>
          <el-button size="mini" type="text" @click="deleteMember(row)">
            <span class="gl_color_error">移除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="text-align: center;" class="gl_pb_15">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="registerQO.MaxResultCount"
        :current-page="registerQO.Page"
        @size-change="changePageSize"
        @current-change="changePage"
      />
    </el-row>

    <el-dialog class="gl_dialog_TitleLine" :title="editMemberTitle" :visible.sync="dialogVisibleForPersonal" :close-on-click-modal="false" width="1200px">
      <div v-loading="dialogVisibleForPersonalLoading" class="gl_px_10">

        <el-tabs v-model="activeTab" class="gl_tabs" type="card">
          <el-tab-pane label="基础信息" name="0">
            <personal-info ref="refPersonalInfo" :user-data="createRegisterInput" :is-default-check="!!(memberInfo && memberInfo.isApproved)" :is-show-tag="true" :is-check="editMemberCode === 'check'" />
          </el-tab-pane>
          <el-tab-pane label="会员信息" name="1">
            <!-- 中跆协会员 -->
            <modMemberInfo ref="refModMemberInfo" :is-check="modIsCheck" :dict="dictRoot.dict" :user-data="createRegisterInput" :hide-title="true" :hide-style="true" class="gl_mb_20" />
          </el-tab-pane>
          <el-tab-pane label="段位信息" name="2">
            <!-- 中跆协级位段位 -->
            <modTkwChiDan ref="refModTkwChiDan" :is-check="modIsCheck" :dict="dictRoot" :user-data="createRegisterInput" :hide-style="true" />

            <!-- 国际台协段位 -->
            <modTkwIntDan ref="refModTkwIntDan" :is-check="modIsCheck" :dict="dictRoot" :user-data="createRegisterInput" :hide-style="true" />
          </el-tab-pane>
        </el-tabs>

        <div slot="footer" class="gl_dl_footer" align="right">
          <el-button v-if="!modIsCheck" size="mini" @click="dialogVisibleForPersonal = false">{{ $t('button.cancel') }}</el-button>
          <el-button v-if="!modIsCheck" size="mini" type="primary" :loading="submitLoading" @click="submitPersonalInfo">{{ $t('button.submit') }}</el-button>
          <el-button v-if="modIsCheck" size="mini" type="primary" @click="dialogVisibleForPersonal = false">{{ $t('button.submit') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { translateByCode } from '@/lib/getTransData';
import {
  Api_GET_EventsManagementRegisterQO,
  SiSTKWEventsManagementCreateRegisterWithTagsInput
} from '@/lib/form/game/swaggerForm';
import {
  api_GET_EventsManagementRegister,
  api_DELETE_EventsManagementDelegationRegisterRegisterId,
  api_GET_EventsManagementRegisterId,
  // api_PUT_EventsManagementRegisterId, // 编辑
  api_POST_EventsManagementRegisterWithtags,
  api_PUT_EventsManagementRegisterIdWithTags
  // api_POST_EventsManagementRegister
} from '@/extend/api/gameswaggerApi/app';
import { CopyData } from '@/lib';
import personalInfo from '@/components/PersonalInfo';
import modMemberInfo from '@/views/home/train/components/modMemberInfo';
import modTkwChiDan from '@/views/home/train/components/modTkwChiDan';
import modTkwIntDan from '@/views/home/train/components/modTkwIntDan';
export default {
  components: {
    personalInfo,
    modMemberInfo,
    modTkwChiDan,
    modTkwIntDan
  },
  data() {
    return {
      registerQO: new Api_GET_EventsManagementRegisterQO(),
      tableData: [],
      total: 0,
      tableLoading: false,
      editMemberTitle: '',
      createRegisterInput: new SiSTKWEventsManagementCreateRegisterWithTagsInput(),
      memberInfo: null,
      dialogVisibleForPersonalLoading: false,
      dialogVisibleForPersonal: false,
      editMemberCode: '', // add、edit、check
      modIsCheck: false,
      activeTab: '0',
      submitLoading: false
    };
  },
  computed: {
    ...mapState({
      currentUserType: state => state.user.currentUserType,
      dictRoot: state => state.dict,
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    })
  },
  watch: {
    'currentUserType': {
      handler: function(val) {
        if (val && val.delegationId) {
          this.delegationId = val.delegationId;
        }
      },
      immediate: true
    }
  },
  created() {
    this.getMemberList();
    this.getDict();
    this.getDictByType(['district']);
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    initForm() {
      this.registerQO = new Api_GET_EventsManagementRegisterQO();
    },
    addressDataForCheck (memberInfo) {
      const _provinceCode = memberInfo.provinceCode;
      const _cityCode = memberInfo.cityCode;
      const _countyCode = memberInfo.countyCode;
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      return `${_provinceData ? _provinceData.name : ''} ${_cityData ? _cityData.name : ''} ${_countyData ? _countyData.name : ''}`;
    },
    // 查询会员列表
    getMemberList(page) {
      if (!this.delegationId) return;
      this.tableLoading = true;
      this.registerQO.Page = page || 1;
      this.registerQO.SkipCount = (this.registerQO.Page - 1) * this.registerQO.MaxResultCount;
      this.registerQO.IsApproved = null;
      this.registerQO.DelegationId = this.currentUserType.delegationId;
      this.registerQO.IncludeTags = true;
      this.registerQO.IncludeRegisterType = true;
      this.registerQO.IncludeIdCardType = true;
      this.registerQO.IncludeGender = true;
      api_GET_EventsManagementRegister(this.registerQO).then(res => {
        this.tableLoading = false;
        this.tableData = res.items || [];
        this.total = res.totalCount;
      }, error => {
        this.tableLoading = false;
        this.$message({ type: 'error', message: (error.error && error.error.message || '') });
      });
    },
    deleteMember(memberInfo) {
      this.$confirm(`您确定要删除会员[ ${memberInfo.name} ]吗？`, '提示', {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_DELETE_EventsManagementDelegationRegisterRegisterId(memberInfo.id).then(res => {
          this.getMemberList(this.registerQO.Page);
          this.$message({ type: 'success', message: '操作成功' });
        }, error => {
          this.$message({ type: 'error', message: (error.error && error.error.message || '') });
        });
      });
    },
    handleOpenEditMemberInfo(typeCode, memberInfo) {
      this.editMemberCode = typeCode;
      this.editMemberTitle = typeCode === 'add' && '新增' || typeCode === 'edit' && '编辑' || typeCode === 'check' && '详情';
      this.modIsCheck = typeCode === 'check';
      this.memberInfo = null;
      this.createRegisterInput = new SiSTKWEventsManagementCreateRegisterWithTagsInput();
      this.createRegisterInput.delegationId = this.delegationId;
      this.createRegisterInput.registerTypeCode = 'I';
      if (memberInfo) {
        this.dialogVisibleForPersonalLoading = true;
        this.getMemberInfo(memberInfo.id).then(res => {
          this.dialogVisibleForPersonalLoading = false;
          this.memberInfo = res;
          this.memberInfo.registerTags = this.memberInfo.registerTags.map(item => item.registerTagTypeCode);
          const _this = this;
          CopyData(_this.memberInfo, _this.createRegisterInput);
          this.createRegisterInput.id = res.id; // modMemberInfo, modTkwChiDan, modTkwIntDan 这三个组件需要个人信息ID
          console.log(this.createRegisterInput);
        }, () => {
          this.dialogVisibleForPersonalLoading = false;
        });
      }
      this.dialogVisibleForPersonal = true;
    },
    // 获取人员信息
    getMemberInfo(id) {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementRegisterId(id, { IncludeTags: true }).then(res => {
          resolve(res);
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: (error.error && error.error.message || '') });
        });
      });
    },
    submitPersonalInfo() {
      this.$refs.refPersonalInfo.getInsideUserData().then(res => {
        this.getFormsData(res);
        // this.addMember(res);
      });
      // this.getFormsData(res);
    },
    // 获取各个表单数据
    getFormsData (vo) {
      const _all = [
        this.$refs['refModMemberInfo'].getInsideUserData(),
        this.$refs['refModTkwChiDan'].getInsideUserData(),
        this.$refs['refModTkwIntDan'].getInsideUserData()
      ];

      Promise.all(_all)
        .then(
          res => {
            this.mergeFormDataToVO(res, vo);
            // editMemberCode: '' // add、edit、check

            if (this.editMemberCode === 'edit') {
              this.updateMemberInfo(vo);
            } else if (this.editMemberCode === 'add') {
              this.addMember(vo);

            }
          }
        )
        .catch(
          error => {
            console.log('error: ', error);
            this.$message({
              message: `请先完善必填信息`,
              type: 'warning',
              showClose: true
            });
            if (error.component === 'memberInfo') {
              this.activeTab = '1';
            }
            if (error.component === 'tkwIntDan' || error.component === 'tkwChiDan') {
              this.activeTab = '2';
            }
          }
        );
    },
    // 将数据合并到VO
    mergeFormDataToVO (list, vo) {
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        CopyData(item, vo);
      }
    },
    // 添加人员
    addMember(data) {
      this.submitLoading = true;
      // 将空字符串转为Null, 部分后端类型不支持null. 所以移除为空字段
      const vo = JSON.parse(JSON.stringify(data));
      for (const k in vo) {
        const ktem = vo[k];
        if (ktem === '' || ktem === null) {
          // vo[k] = null;
          delete vo[k];
        }
      }
      vo.isCurrentUser = false;
      vo.joinCurrentDelegation = true;
      console.log(vo);
      api_POST_EventsManagementRegisterWithtags(vo).then(() => {
        this.submitLoading = false;
        this.$message({ type: 'success', message: this.memberInfo ? '编辑成功' : '新增成功' });
        this.dialogVisibleForPersonal = false;
        this.getMemberList(this.registerQO.Page);
      }, error => {
        this.submitLoading = false;
        this.$message({ type: 'error', message: (error.error && error.error.message || '') });
      });
    },
    // 更新个人信息
    updateMemberInfo(data) {
      this.submitLoading = true;
      // 将空字符串转为Null, 部分后端类型不支持null. 所以移除为空字段
      const vo = JSON.parse(JSON.stringify(data));
      for (const k in vo) {
        const ktem = vo[k];
        if (ktem === '' || ktem === null) {
          // vo[k] = null;
          delete vo[k];
        }
      }
      api_PUT_EventsManagementRegisterIdWithTags(this.memberInfo.id, vo).then(() => {
        this.submitLoading = false;
        this.dialogVisibleForPersonal = false;
        this.getMemberList(this.registerQO.Page);
        this.$message({ type: 'success', message: '编辑成功' });
      }, error => {
        this.submitLoading = false;
        this.$message({ type: 'error', message: (error.error && error.error.message) });
      });
    },
    changePage(page) {
      this.getMemberList(page);
    },
    changePageSize(pagesize) {
      this.registerQO.MaxResultCount = pagesize;
      this.getMemberList();
    },
    getStaticAvatarUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    }
  }
};
</script>
<style>
.game_coverimg {
  max-width: 74px;
  max-height: 74px;
  border-radius: 50%;
}
.show_avatar{
  background-size: 100% 100%;
}

  .box_wrap {
    padding: 30px 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0px 10px 36px 0px rgba(0, 0, 0, 0.08);
  }
  .box_wrap_title {
    font-size: 16px;
    font-weight: 500;
    line-height: 22px;
    color: #353434;
    margin-bottom: 20px;
  }
</style>
